package com.pcdotfan.zhengfang.controller;

import com.pcdotfan.zhengfang.exception.NotFoundException;
import com.pcdotfan.zhengfang.model.Student;
import com.pcdotfan.zhengfang.model.Test;
import com.pcdotfan.zhengfang.repository.StudentRepository;
import com.pcdotfan.zhengfang.repository.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class TestController {
	
	@Autowired
	private TestRepository testRepository;

	@GetMapping("/tests")
	public List<Test> retrieveAllTest() {
		return testRepository.findAll();
	}

	@GetMapping("/tests/{id}")
	public Test retrieveTest(@PathVariable long id) {
		Optional<Test> test = testRepository.findById(id);

		if (!test.isPresent())
			throw new NotFoundException("id-" + id);

		return test.get();
	}

	@DeleteMapping("/tests/{id}")
	public void deleteTest(@PathVariable long id) {
		testRepository.deleteById(id);
	}

	@PostMapping("/tests")
	public ResponseEntity<Object> createStudent(@RequestBody Test test) {
		Test savedTest = testRepository.save(test);

		URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
				.buildAndExpand(savedTest.getId()).toUri();

		return ResponseEntity.created(location).build();
	}

	@PutMapping("/tests/{id}")
	public ResponseEntity<Object> updateTest(@RequestBody Test test, @PathVariable long id) {

		Optional<Test> testOptional = testRepository.findById(id);

		if (!testOptional.isPresent())
			return ResponseEntity.notFound().build();

		test.setId(id);

		testRepository.save(test);

		return ResponseEntity.noContent().build();
	}
	
}
